package com.saic.data.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.IOUtils;

/**
 * @对文件的操作
 * @author Xinshiyou
 */
public class FileUtil {

	/**
	 * @打开文件：如果不存在，创建File
	 * 
	 * @param path
	 * @param isCreate
	 * @throws IOException
	 */
	public static File open(String path, boolean isCreate) throws IOException {
		File file = new File(path);
		if (!file.exists()) {
			if (isCreate) {
				if (file.isDirectory())
					file.mkdir();
				else
					file.createNewFile();
			}
		}
		return file;
	}

	/**
	 * @读文件：返回列表
	 * @param file
	 * @return
	 * @throws IOException
	 */
	public static List<String> read(File file) throws IOException {

		String line;
		List<String> list = new ArrayList<String>();
		BufferedReader br = null;
		try {
			br = new BufferedReader(new InputStreamReader(new FileInputStream(
					file)));
			while (null != (line = br.readLine())) {
				list.add(line.trim());
			}
		} finally {
			if (null != br)
				br.close();
		}
		return list;
	}

	/**
	 * @读文
	 * @param fileName
	 * @return
	 * @throws IOException
	 */
	public static List<String> read(String fileName) throws IOException {
		File file = open(fileName, false);
		return read(file);
	}

	/**
	 * @按行写入文件
	 * @param fileName
	 * @param list
	 * @throws IOException
	 */
	public static void write(String fileName, List<String> list)
			throws IOException {
		File file = open(fileName, true);
		FileWriter fw = new FileWriter(file);
		for (String s : list) {
			fw.write(s + "\n");
		}
		fw.flush();
		fw.close();
		file = null;
	}

	/**
	 * @写入文件
	 * @param fileName
	 * @param list
	 * @param sep
	 *            -旧的分隔
	 * @param newSep
	 *            -新的分隔
	 * @throws IOException
	 */
	public static void write(String fileName, List<String> list, String sep,
			String newSep) throws IOException {
		File file = open(fileName, true);
		FileWriter fw = new FileWriter(file);
		for (String s : list) {
			String[] tmp = s.trim().split(sep);
			for (String t : tmp)
				fw.write(t + newSep);
			fw.write("\n");
		}
		fw.flush();
		fw.close();
		file = null;
	}

	/**
	 * @获取文件的MD5码,并关闭文件：效率较高
	 * @param in
	 * @return
	 * @throws IOException
	 */
	public static String getMD5(InputStream in) throws IOException {
		String res = DigestUtils.md5Hex(in);
		IOUtils.closeQuietly(in);
		return res;
	}

	/**
	 * @获得文件的MD5码：效率较低
	 * @param file
	 * @return
	 * @throws FileNotFoundException
	 */
	public static String getMD5(File file) throws FileNotFoundException {
		String value = null;
		FileInputStream in = new FileInputStream(file);
		try {
			MappedByteBuffer byteBuffer = in.getChannel().map(
					FileChannel.MapMode.READ_ONLY, 0, file.length());
			MessageDigest md5 = MessageDigest.getInstance("MD5");
			md5.update(byteBuffer);
			BigInteger bi = new BigInteger(1, md5.digest());
			value = bi.toString(16);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			IOUtils.closeQuietly(in);
		}
		return value;
	}
	
	public static String getMD5(String txt) {
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(txt.getBytes());
			byte[] b = md.digest();

			int i;
			StringBuffer buf = new StringBuffer("");
			for (int offset = 0; offset < b.length; offset++) {
				i = b[offset];
				if (i < 0)
					i += 256;
				if (i < 16)
					buf.append("0");
				buf.append(Integer.toHexString(i));
			}
			return buf.toString();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * @自动生成UUID唯一标识
	 * @return
	 */
	public static String getUUID() {
		String s = UUID.randomUUID().toString();
		return s.substring(0, 8) + s.substring(9, 13) + s.substring(14, 18)
				+ s.substring(19, 23) + s.substring(24);
	}
	/**
	 * @获取文件扩展名
	 * @return
	 */
	public static String getType(String filename) {
		String[] tmp = filename.split("\\.");
		return tmp[tmp.length - 1].toLowerCase();
	}
	/**
	 * @获取文件名
	 * @return
	 */
	public static String getName(String filename) {
		String[] tmp = filename.split("\\.");
		return tmp[0];
	}

}
